<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="部门名称" prop="deptName">
                <el-input
                        v-model="queryParams.deptName"
                        placeholder="请输入部门名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="状态 " prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态 " clearable>
                    <el-option
                            v-for="dict in sys_normal_disable"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['system:dept:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="info"
                        plain
                        icon="Sort"
                        @click="toggleExpandAll"
                >展开/折叠
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getTreeList"></right-toolbar>
        </el-row>

        <el-table
                v-if="refreshTable"
                v-loading="loading"
                :data="deptList"
                row-key="id"
                :default-expand-all="isExpandAll"
                :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
            <el-table-column label="部门名称" align="left" min-width="120" prop="deptName" show-overflow-tooltip/>
            <el-table-column label="排序" align="center" prop="orderNum"/>
            <el-table-column label="状态 " align="center" prop="status">
                <template #default="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button
                            type="primary"
                            text
                            icon="Edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['system:dept:edit']"
                    >修改
                    </el-button>
                    <el-button
                            type="primary"
                            text
                            icon="Plus"
                            @click="handleAdd(scope.row)"
                            v-hasPermi="['system:dept:add']"
                    >新增
                    </el-button>
                    <el-button
                            type="danger"
                            text
                            icon="Delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['system:dept:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加或修改部门对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form v-if="open" ref="deptRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="上级部门" prop="parentId">
                    <el-tree-select
                        v-model="form.parentId"
                        :data="deptOptions"
                        :props="{ value: 'id', label: 'label', children: 'children' }"
                        value-key="id"
                        placeholder="请选择上级部门"
                        check-strictly
                    />
                </el-form-item>
                <el-form-item label="部门名称" prop="deptName">
                    <el-input v-model="form.deptName" placeholder="请输入部门名称"/>
                </el-form-item>
                <el-form-item label="显示顺序" prop="orderNum">
                    <el-input-number v-model="form.orderNum" controls-position="right" placeholder="请输入显示顺序"/>
                </el-form-item>
                <el-form-item label="状态 ">
                    <el-radio-group v-model="form.status">
                        <el-radio
                                v-for="dict in sys_normal_disable"
                                :key="dict.value"
                                :value="dict.value"
                        >{{ dict.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="负责人" prop="chargePerson">
                    <el-input v-model="form.chargePerson" placeholder="请输入负责人"/>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入联系电话"/>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Dept">
import {listTreeDept, treeSelect, getDept, delDept, addDept, updateDept} from "@/api/system/dept";
import {getCurrentInstance, nextTick, reactive, ref, toRefs} from "vue";

const {proxy} = getCurrentInstance();
const {sys_normal_disable} = proxy.initDict('sys_normal_disable');

const deptList = ref([]);
const deptOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
    form: {},
    queryParams: {
        deptName: null,
        status: null
    },
    rules: {
        parentId: [
            {required: true, message: '请选择上级菜单', trigger: 'change'}
        ],
        deptName: [
            {required: true, message: '请输入部门名称', trigger: 'blur'}
        ],
        orderNum: [
            {required: true, message: '请输入显示顺序', trigger: 'blur'}
        ],
        status: [
            {required: true, message: '请选择状态', trigger: 'change'}
        ]
    }
});

const {queryParams, form, rules} = toRefs(data);

getTreeList();

/** 查询部门树列表 */
function getTreeList() {
    loading.value = true;
    listTreeDept(queryParams.value).then(response => {
        deptList.value = response.data;
        loading.value = false;
    });
}

/** 查询部门下拉树结构 */
function getTreeSelect() {
    treeSelect().then(response => {
        deptOptions.value = [];
        const data = {id: 0, label: '顶级部门', children: []};
        data.children = response.data;
        deptOptions.value.push(data);
    });
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        createBy: null,
        createTime: null,
        deleteFlag: null,
        remark: null,
        updateBy: null,
        updateTime: null,
        ancestors: null,
        chargePerson: null,
        deptName: null,
        orderNum: 0,
        parentId: null,
        phone: null,
        status: "0"
    };
    proxy.resetForm("deptRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    getTreeList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
    reset();
    getTreeSelect();
    if (row != null && row.id) {
        form.value.parentId = row.id;
    } else {
        form.value.parentId = 0;
    }
    open.value = true;
    title.value = "添加部门";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
    refreshTable.value = false;
    isExpandAll.value = !isExpandAll.value;
    nextTick(() => {
        refreshTable.value = true;
    });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
    reset();
    await getTreeSelect();
    if (row != null) {
        form.value.parentId = row.id;
    }
    getDept(row.id).then(response => {
        form.value = response.data;
        open.value = true;
        title.value = "修改部门";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["deptRef"].validate(valid => {
        if (valid) {
            if (form.value.id != null) {
                updateDept(form.value).then(response => {
                    proxy.$message.success("修改成功");
                    open.value = false;
                    getTreeList();
                });
            } else {
                addDept(form.value).then(response => {
                    proxy.$message.success("新增成功");
                    open.value = false;
                    getTreeList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    proxy.$messageBox.confirm('是否确认删除部门编号为"' + row.id + '"的数据项？').then(function () {
        return delDept(row.id);
    }).then(() => {
        getTreeList();
        proxy.$message.success("删除成功");
    }).catch(() => {
    });
}

</script>
